﻿// Copyright (c) Vitaly Kamiansky. All rights reserved. 
// See License.txt in the project root.

using System;

namespace Property.Reloaders
{
    public class ThrottleReloaderDecorator<T> : ReloaderDecorator<T>
    {
        public ThrottleReloaderDecorator(IReloaderPrototype<T> compositionBasePrototype, 
            Func<T> getValue, Action<T> applyValue, Action<bool> applyStatus, 
            ITimerPrototype timerPrototype)
            : base(compositionBasePrototype, getValue, applyValue, applyStatus)
        {
            if (timerPrototype == null) throw new ArgumentNullException("timerPrototype");

            _Timer = timerPrototype.Create();

            if (_Timer == null) throw new NotSupportedException(StringsCallbacks.CANT_OBTAIN_TIMER);

            _Timer.Tick += Pass;
        }

        //=//

        private readonly ITimer _Timer;

        private void Pass(object sender, EventArgs e)
        {
            _Timer.Stop();
            _CompositionBase.Go();
        }

        public override void Go()
        {
            _Timer.Stop();
            _Timer.Start();
        }

        public override void Dispose()
        {
            _Timer.Tick -= Pass;
            _Timer.Dispose();
            base.Dispose();
        }
    }
}
